const importService = require('../services/importService');
const validationService = require('../services/validationService');
const { Score, Student, ImportLog } = require('../models');
const { Op } = require('sequelize');

/**
 * 成绩控制器
 */
class ScoreController {
  /**
   * 导入 Excel 文件
   */
  async importScores(req, res) {
    try {
      // 检查文件
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '请上传 Excel 文件'
        });
      }

      // 验证文件格式
      const allowedExtensions = ['.xlsx', '.xls'];
      const fileExtension = req.file.originalname.toLowerCase().slice(req.file.originalname.lastIndexOf('.'));
      
      if (!allowedExtensions.includes(fileExtension)) {
        return res.status(400).json({
          success: false,
          message: '文件格式不支持，仅支持 .xlsx 和 .xls 格式'
        });
      }

      // 验证上传参数
      const paramsValidation = validationService.validateUploadParams({
        examName: req.body.examName,
        examDate: req.body.examDate
      });

      if (!paramsValidation.valid) {
        return res.status(400).json({
          success: false,
          message: paramsValidation.error
        });
      }

      // 导入文件
      const result = await importService.importExcelFile(
        req.file.path,
        req.file.originalname,
        paramsValidation.data.examName,
        paramsValidation.data.examDate
      );

      res.json(result);
    } catch (error) {
      console.error('导入失败:', error);
      res.status(500).json({
        success: false,
        message: `导入失败: ${error.message}`
      });
    }
  }

  /**
   * 查询成绩
   */
  async queryScores(req, res) {
    try {
      const {
        studentId,
        name,
        className,
        startDate,
        endDate,
        page = 1,
        pageSize = 20
      } = req.query;

      // 构建查询条件
      const where = {};
      
      if (studentId) {
        where.student_id = { [Op.like]: `%${studentId}%` };
      }
      
      if (startDate || endDate) {
        where.exam_date = {};
        if (startDate) {
          where.exam_date[Op.gte] = startDate;
        }
        if (endDate) {
          where.exam_date[Op.lte] = endDate;
        }
      }

      // 构建学生表查询条件
      const studentWhere = {};
      if (name) {
        studentWhere.name = { [Op.like]: `%${name}%` };
      }
      if (className) {
        studentWhere.class_name = { [Op.like]: `%${className}%` };
      }

      // 如果有姓名或班级查询，需要关联学生表
      const include = [{
        model: Student,
        as: 'student',
        attributes: ['name', 'class_name'],
        where: (name || className) ? studentWhere : undefined
      }];

      // 分页参数
      const limit = Math.min(parseInt(pageSize), 100);
      const offset = (parseInt(page) - 1) * limit;

      // 查询数据
      const { count, rows } = await Score.findAndCountAll({
        where,
        include,
        limit,
        offset,
        order: [['exam_date', 'DESC'], ['school_rank', 'ASC']]
      });

      // 格式化结果
      const records = rows.map(score => ({
        id: score.id,
        studentId: score.student_id,
        name: score.student?.name,
        className: score.student?.class_name,
        examName: score.exam_name,
        examDate: score.exam_date,
        chinese: score.chinese,
        math: score.math,
        english: score.english,
        physics: score.physics,
        chemistry: score.chemistry,
        biology: score.biology,
        politics: score.politics,
        history: score.history,
        geography: score.geography,
        totalScore: score.total_score,
        schoolRank: score.school_rank,
        createdAt: score.created_at,
        updatedAt: score.updated_at
      }));

      res.json({
        success: true,
        data: {
          records,
          total: count,
          page: parseInt(page),
          pageSize: limit
        },
        message: count === 0 ? '未找到相关记录' : undefined
      });
    } catch (error) {
      console.error('查询失败:', error);
      res.status(500).json({
        success: false,
        message: `查询失败: ${error.message}`
      });
    }
  }

  /**
   * 获取导入历史
   */
  async getImportLogs(req, res) {
    try {
      const { page = 1, pageSize = 20 } = req.query;

      const limit = Math.min(parseInt(pageSize), 100);
      const offset = (parseInt(page) - 1) * limit;

      const { count, rows } = await ImportLog.findAndCountAll({
        limit,
        offset,
        order: [['created_at', 'DESC']]
      });

      res.json({
        success: true,
        data: {
          logs: rows,
          total: count,
          page: parseInt(page),
          pageSize: limit
        }
      });
    } catch (error) {
      console.error('获取导入历史失败:', error);
      res.status(500).json({
        success: false,
        message: `获取导入历史失败: ${error.message}`
      });
    }
  }

  /**
   * 获取导入错误详情
   */
  async getImportErrors(req, res) {
    try {
      const { id } = req.params;

      const importLog = await ImportLog.findByPk(id);

      if (!importLog) {
        return res.status(404).json({
          success: false,
          message: '导入记录不存在'
        });
      }

      res.json({
        success: true,
        data: {
          importId: importLog.id,
          filename: importLog.filename,
          errors: importLog.error_details || []
        }
      });
    } catch (error) {
      console.error('获取错误详情失败:', error);
      res.status(500).json({
        success: false,
        message: `获取错误详情失败: ${error.message}`
      });
    }
  }
}

module.exports = new ScoreController();
